// pages/index/index.js
import {getChannel, getArticles, getAllChannels} from '../../api/index.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    channelList: [],
    articalList: [],
    allChannelList: [],
    refresher: false,
    params: {
      channel_id: 0,
      with_top: 1,
      timestamp: +new Date(),
    },
    loadingText: '释放即可刷新...',
    refresher: false,
  },

  onClickLeft() {
    wx.navigateBack()
  },

  openBtn() {
    this.setData({
      show: true
    })
  },

  onClose() {
    this.setData({ show: false });
  },

  toSearch() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },

  toDetail(e) {
    console.log(e)
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + e.currentTarget.dataset.id,
    })
  },

  // 获取用户频道
  async getChannel() {
    const res = await getChannel()
    this.setData({
      channelList: res.data.channels
    })
  },

  // 获取所有频道
  async getAllChannels() {
    const res = await getAllChannels()
    console.log(res)
    const arr = []
    res.data.channels.forEach(item => {
      if(!this.data.channelList.some(item1 => item1.id === item.id)) {
        arr.push(item)
      }
    })
    this.setData({
      allChannelList: arr
    })
  },

  // 添加频道
  async addChannels(e) {
    console.log(e)
  },
  // 上拉刷新
  async onPulling() {
    this.setData({
      loadingText: '加载中...',
      'params.timestamp': +new Date()
    })
    try {
      const res = await getArticles(this.data.params)
      this.setData({
       articalList: [this.data.articalList, ...res.data.results],
      })
    } finally {
      setTimeout(() => {
        this.setData({
          refresher: false,
        })
      }, 1000)
    }
  },

  // 切换tab
  onChangeTab(e) {
    this.setData({
      'params.channel_id': e.detail.name,
      articalList: []
    })
    this.getAtrcles()
  },

  // 获取新闻列表
   async getAtrcles() {
     const res = await getArticles(this.data.params)
     this.setData({
      articalList: [...this.data.articalList, ...res.data.results],
     })
  },
  /**
   * 生命周期函数--监听页面加载
   */
   async onLoad(options) {
    this.getChannel()
    this.getAtrcles()
    this.getAllChannels()
    await this.selectComponent('#tabs').resize()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.setData({
      'params.timestamp': +new Date()
    })
    this.getAtrcles()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})